package run;

/*
 * ServerFrame.java   2001-02-08
 *
 * Copyright (c) 2001 Robert Laganiere and Timothy C. Lethbridge.
 * All Rights Reserved.
 *
 */

//ff

import java.awt.*;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import control.ConnectionManage;
import db.parking.beans.Parking;
import db.parking.beans.ParkingLot;
import db.parking.beans.rates;
import db.tables.AdminParking;
import db.tables.AdminRates;
import db.tables.ParkingLotAdmin;
import server.SimpleServer;

/**
 * The <code> ServerFrame </code> class is a simple interactive application made
 * to exercise the OCSF framework.
 * <p>
 * Type <code>java ocsftester.ServerFrame port_number</code> to start the
 * server.
 * <p>
 * The window is red when the server is closed, yellow when the server is
 * stopped and green when open.
 * 
 * @author Dr. Robert Lagani&egrave;re
 * @version February 2001
 * @see ocsftester.SimpleServer
 */
public class ServerFrame extends Frame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Button closeB = new Button("Close");
	private Button listenB = new Button("Listen");
	private Button quitB = new Button("Quit");
	private TextField port = new TextField("12345");
	private TextField backlog = new TextField("5");
	private TextField timeout = new TextField("500");

	private TextField dbUser = new TextField("root");
	private TextField dbPass = new TextField();
	private TextField dbName = new TextField();
	
	private TextField dbHost = new TextField("localhost");
	private TextField dbPort = new TextField("3306");

	private Label lblDBU = new Label("DB username:", Label.RIGHT);
	private Label lblDBP = new Label("DB pass:", Label.RIGHT);
	private Label lblDBNAME = new Label("DB name:", Label.RIGHT);
	
	private Label lblDBH = new Label("DB host:", Label.RIGHT);
	private Label lblDBPP = new Label("DB port:", Label.RIGHT);

	private Label portLB = new Label("Server Port: ", Label.RIGHT);
	private Label timeoutLB = new Label("Conn Timeout: ", Label.RIGHT);
	private Label backlogLB = new Label("Conn Backlog: ", Label.RIGHT);
	private List liste = new List();
	private SimpleServer server;
	private ParkingLot Lot[];
	private final int ParkingLotNum = 6;

	public ServerFrame(int p) throws SQLException {
		super("OCSF Server");
		server = new SimpleServer(p, liste);
		port.setText(String.valueOf(p));

		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				quit();
			}
		});

		quitB.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				quit();
			}
		});

		closeB.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				close();
			}
		});

		listenB.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				listen();
			}
		});
        
		InetAddress addr = InetAddress.getLoopbackAddress();
		this.dbHost.setText(addr.getHostAddress());
		this.dbName.setText("vcp");
		
		
		
		Panel bottom = new Panel();
		bottom.setLayout(new GridLayout(10, 2, 5, 5));
		bottom.add(lblDBNAME);
		bottom.add(dbName);
		bottom.add(lblDBU);
		bottom.add(dbUser);
		bottom.add(lblDBP);
		bottom.add(dbPass);
		bottom.add(lblDBH);
		bottom.add(dbHost);
		bottom.add(lblDBPP);
		bottom.add(dbPort);
		bottom.add(portLB);
		bottom.add(port);
		bottom.add(backlogLB);
		bottom.add(backlog);
		bottom.add(timeoutLB);
		bottom.add(timeout);
		bottom.add(listenB);
		bottom.add(closeB);
		bottom.add(quitB);

		setLayout(new BorderLayout(5, 5));
		add("Center", liste);
		add("South", bottom);
		setSize(450, 400);
		setVisible(true);
	}

	public List getListe() {
		return liste;
	}

	public void setListe(List liste) {
		this.liste = liste;
	}

	public SimpleServer getServer() {
		return server;
	}

	public void setServer(SimpleServer server) {
		this.server = server;
	}

	/*
	 * private void InitParkingLot() throws SQLException { Lot = new
	 * ParkingLot[ParkingLotNum]; rates rateDB[] = AdminRates.getRows(); Parking
	 * parkDB[] = AdminParking.getRows();
	 * 
	 * for(int i=0;i<ParkingLotNum;i++) { ParkingLot dbLot =
	 * ParkingLotAdmin.getRow(i+1); Lot[i] = new ParkingLot(dbLot); }
	 * 
	 * for(int j=0;j<30;j++) {
	 * Lot[rateDB[j].getLotNo()-1].setPrices(rateDB[j].getAmount
	 * (),rateDB[j].getRateType()-1); }
	 * 
	 * for(int i=0;i<parkDB.length;i++) {
	 * Lot[(parkDB[i].getLotNo())-1].setLocation
	 * (parkDB[i].getPositionX(),parkDB[
	 * i].getPositionY(),parkDB[i].getFloorNo(),parkDB[i].getStatus());
	 * 
	 * }
	 * 
	 * 
	 * }
	 */

	private boolean readFields() {
		int p = Integer.parseInt(port.getText());
		int t = Integer.parseInt(timeout.getText());
		int b = Integer.parseInt(backlog.getText());

		server.setPort(p);
		server.setBacklog(b);
		server.setTimeout(t);

		// db conn setup
		String user = dbUser.getText();
		String pass = dbPass.getText();
		String host = dbHost.getText();
		String port = dbPort.getText();
		String dbname = dbName.getText();
		ConnectionManage cmgr = ConnectionManage.getInstance();
		cmgr.setUSERNAME(user);
		cmgr.setPASSWORD(pass);
		cmgr.setHost(host);
		cmgr.setPort(port);
		cmgr.setDBNAME(dbname);
		if(cmgr.getConnection()!=null){
			return true;
		}else{
			JOptionPane.showMessageDialog(null,
					"Please review all fields, can't open connection, see stacktrace...", "Error",
					JOptionPane.ERROR_MESSAGE); 
			return false;
		}
		
	}

	public TextField getDbUser() {
		return dbUser;
	}

	public void setDbUser(String ste) {	
		this.dbUser.setText(ste);
	}

	public TextField getDbPass() {
		return dbPass;
	}

	public void setDbPass(String dbPass) {
		this.dbPass.setText(dbPass);
	}

	public TextField getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName.setText(dbName);
	}

	public TextField getDbHost() {
		return dbHost;
	}

	public void setDbHost(String dbHost) {
		this.dbHost.setText(dbHost);
	}

	public TextField getDbPort() {
		return dbPort;
	}

	public void setDbPort(String dbPort) {
		this.dbPort.setText(dbPort);
	}

	public void close() {
		System.out
				.println("Number of clients = " + server.getNumberOfClients());
		try {
			readFields();
			server.close();
		} catch (Exception ex) {
			liste.add(ex.toString());
			liste.makeVisible(liste.getItemCount() - 1);
			liste.setBackground(Color.red);
		}
	}

	public void listen() {
		/*
		System.out
				.println("Number of clients = " + server.getNumberOfClients());
		*/
		try {
			if(readFields())
			   server.listen();
		} catch (Exception ex) {
			liste.add(ex.toString());
			liste.makeVisible(liste.getItemCount() - 1);
			liste.setBackground(Color.red);
		}
	}

	public void stop() {
		System.out
				.println("Number of clients = " + server.getNumberOfClients());
		readFields();
		server.stopListening();
	}

	public void quit() {
		System.exit(0);
	}
	
	
	public static boolean isLocalAddr(InetAddress addr) {
	    if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
	        return true;
		return false;
	}

	/**
	 * Starts the server. The default port is 12345.
	 * 
	 * @throws SQLException
	 */
	public static void main(String[] arg) throws SQLException {
		@SuppressWarnings("unused")
		ServerFrame sf;
		if (arg.length == 0)
			sf = new ServerFrame(12345);
		if (arg.length == 1)
			sf = new ServerFrame(Integer.parseInt(arg[0]));
	}
}